﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace FileFolderOperations
{
    public class FileFunctions
    {

        private String sSource = "FileFunctions";
        private String sLog = "Application";

        public FileFunctions()
        {
            if (!EventLog.SourceExists(sSource))
                EventLog.CreateEventSource(sSource, sLog);
            EventLog.WriteEntry(sSource, "Constructor Started");
        }
        public bool deleteFile(String fileLocation)
        {
            bool isDeleted = true;
            if (System.IO.File.Exists(fileLocation))
            {
                // Use a try block to catch IOExceptions, to
                // handle the case of the file already being
                // opened by another process.
                try
                {
                    System.IO.File.Delete(fileLocation);
                }
                catch (System.IO.IOException e)
                {
                    EventLog.WriteEntry(sSource, "Error deleting file-"+e.Message, EventLogEntryType.Error);
                    isDeleted = false;
                }
            }

            return isDeleted;

        }

        public bool copyFile(String sourceFile, String targetFolder)
        {
            bool isCopySuccess = true;

            try
            {
                    
                if (!System.IO.Directory.Exists(targetFolder))
                {
                    System.IO.Directory.CreateDirectory(targetFolder);
                }

                // To copy a file to another location and 
                // overwrite the destination file if it already existss
                String [] splittedString = sourceFile.Split('\\');
                String targetFile = targetFolder + splittedString[splittedString.Length - 1];
                
                System.IO.File.Copy(sourceFile, targetFile, true);

            }
            catch (Exception generalException)
            {
                isCopySuccess = false;
                // log this information in the event logger
                EventLog.WriteEntry(sSource, "Error copying file-"+sourceFile+" "+generalException.Message, EventLogEntryType.Error);

            }

            return isCopySuccess;

        }

    }
}
